<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\home\controller;

use app\common\model\SysNotice;
use buwang\facade\Http;
use buwang\facade\Rpc;
use think\facade\Db;
use think\facade\View;
use app\common\model\Miniapp;

class Index extends Basic
{
    use \buwang\traits\JumpTrait;
    use \buwang\traits\JwtTrait;
    public function test()
    {
        $res = \buwang\util\console\CliRun::execute(root_path(), "php think mn-seed:run install -s UpdateSeedNew");
        var_dump($res);

    }
    public function index()
    {

//        $default = \app\common\model\Config::getConfigData('storage', 'default', 'local');
//        $res =\app\common\model\Config::getConfigData('storage',$default , 'local');
//        var_dump($res);die;
        //$miniapps = array_flip(Miniapp::column('dir', 'id')); //以目录名为key 应用id为value的数组
        //var_dump($miniapps);die;
        //var_dump($this->app->route->getRuleList());die;
        $where = ['status'=>1,'is_diy'=> 0];
        $list = Miniapp::where($where)->order(['sort'=>'desc'])->limit(0,12)->select();
        View::assign('list', $list);
        if($this->request->isMobile()){
            $this->app->view->engine()->layout(false);
            return view('/index/mobile');
        }
        return view();
    }
    public function store(){
        $where = ['status'=>1,'is_diy'=> 0];
        $list = Miniapp::where($where)->order(['sort'=>'desc'])->limit(0,12)->select();
        View::assign('list', $list);
        return view();
    }
    public function news(){
        $limit = $this->request->get('limit', 10);
        $where = [];
        $list = SysNotice::where($where)->field("id,title,add_time")->order('add_time desc,id desc')->paginate($limit);
        $page = $list->render();
        View::assign('page',$page);
        View::assign('list', $list);
        return view();
    }
    public function newsDetail(){
        $news_id = (int) $this->request->param('id');
        if(!$news = SysNotice::find($news_id)){
            $this->error_jump('不存在该新闻',NOT_JUMP);
        }
        $this->assign('news',$news);
        return view();
    }
    public function about(){
        return view();
    }
    public function join(){
        return view();
    }
    public function help(){
        return view();
    }

    public function hello($name = 'ThinkPHP6')
    {
        $data=Db::name('computer')->where('id', 8)->find();
        //有库存
        if ($data['num'] >0 ){
            //库存减一
            $res = Db::name('computer')->where('id', 8)->dec('num')->update();
            if ($res) {
                            dump('资源操作成功：');
                trace('资源操作成功：' . time(), 'error');
            }
        }

//        $processNum = 5000; //5万个进程
//        //表里id等于8的num数量为10
//        //5万进程抢10个数量
//        for ($i = 0; $i < $processNum; $i++) {
            //实例化
//            $redisLoke=new RedisLockService("jackhhy_key");
//            //获取redis锁
//            $locked=$redisLoke->Getlock();
//
//            if ($locked){
//                //获取锁成功
//                Db::startTrans();
//                try{
//                    $data=Db::name('computer')->where('id', 8)->lock(true)->find();
//                    //有库存
//                    if ($data['num'] >0 ){
//                        //库存减一
//                        $res = Db::name('computer')->where('id', 8)->dec('num')->update();
//                        if ($res) {
////                            dump('资源操作成功：');
//                            trace('资源操作成功：' . time(), 'error');
//                        }
//                    }
//                    Db::commit();
//                }catch (\Exception $exception){
//                    dump($exception->getMessage());
//                    Db::rollback();
//                }finally{
//                    //释放锁
//                    $redisLoke->Unlock();
//                }
//            }
//        }
    }

    public function http()
    {
        //$response = Http::get('https://www.baidu.com');
        //var_dump($response);
        //session('res', '$response->body()');
        file_put_contents('111.txt', time() . PHP_EOL, FILE_APPEND);
        Http::getAsync('https://api.wohuiliao.com', [], function (\http\Response $response) {
            sleep(5);
            echo '异步请求成功，响应内容：' . $response->body() . PHP_EOL;
            file_put_contents('111.txt', $response->body() . time() . PHP_EOL, FILE_APPEND);
        }, function (\http\RequestException $e) {
            echo '异步请求异常，错误码：' . $e->getCode() . '，错误信息：' . $e->getMessage() . PHP_EOL;
            session('res', '1211');
            file_put_contents('111.txt', '34343');
        });
        var_dump(file_get_contents('111.txt'));

        //echo json_encode(['code' => 200, 'msg' => '请求成功'], JSON_UNESCAPED_UNICODE) . PHP_EOL;


//        $obj = new Https();
//        $obj->asyncGet('https://api.wohuiliao.com/');


    }

    public function httpnew()
    {

        $promises = [
            Http::getAsync('https://api.wohuiliao.com'),
            Http::getAsync('https://api.wohuiliao.com', ['name' => 'gouguoyin']),
            Http::postAsync('https://www.baidu.com', ['name' => 'gouguoyin']),
        ];

        Http::concurrency(3)->multiAsync($promises, function (\http\Response $response, $index) {
            file_put_contents('222.txt', $index . '---' . $response->body() . time() . PHP_EOL, FILE_APPEND);

            echo "发起第 $index 个异步请求，请求时长：" . $response->json()->second . '秒' . PHP_EOL;
        }, function (\http\RequestException $e, $index) {
            echo "发起第 $index 个请求失败，失败原因：" . $e->getMessage() . PHP_EOL;
        });
        var_dump(file_get_contents('222.txt'));
    }

    public function data()
    {
        $data = ['key' => 'value'];
        //R()->code(403)->error('失败',$data,400009);
        R()->success($data);
    }

    public function send_rpc()
    {
        $serve = 'tcp://47.92.77.33:9600';
        $data = [
            'command' => 1,//1:请求,2:状态rpc 各个服务的状态
            'request' => [
                'serviceName' => 'common',
                'action' => 'mailBox',//行为名称
                'arg' => [
                    'args1' => 'args1',
                    'args2' => 'args2'
                ]
            ]
        ];

        Rpc::send($serve, $data, function (...$data) {
            var_dump($data);
        });
    }

}
